package com.zscat.mallplus.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.DialectFactory;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zscat.mallplus.annotation.IgnoreAuth;
import com.zscat.mallplus.annotation.SysLog;
import com.zscat.mallplus.dms.entity.DmsOrder;
import com.zscat.mallplus.dms.service.IDeviceService;
import com.zscat.mallplus.dms.service.IDmsOrderService;
import com.zscat.mallplus.dms.service.IMealService;
import com.zscat.mallplus.enums.OrderStatus;
import com.zscat.mallplus.qsg.QsgDevice;
import com.zscat.mallplus.qsg.QsgMeal;
import com.zscat.mallplus.utils.CommonResult;
import com.zscat.mallplus.utils.DateUtil;
import com.zscat.mallplus.utils.ValidatorUtils;
import com.zscat.mallplus.vo.TimeAxis;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 设备管理Controller
 */
@RestController
@Api(tags = "QsgMealController", description = "设备相关管理")
@RequestMapping("/api/dms")
public class QsgMealController {

    @Autowired
    private IMealService mealService;
    @Autowired
    private IDmsOrderService orderService;
    @Autowired
    private IDeviceService deviceService;

    @IgnoreAuth
    @ApiOperation("根据条件查询所有设备套餐管理列表")
    @GetMapping(value = "/meal/list")
    public Object getDeviceByPage(Long storeId) {
        QueryWrapper qw = new QueryWrapper();
        qw.orderByDesc("create_datetime");
        qw.eq("store_id", storeId);
        try {
            return new CommonResult().success(mealService.list(qw));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new CommonResult().failed();
    }

    @IgnoreAuth
    @ApiOperation("保存设备套餐表")
    @PostMapping(value = "/meal/create")
    public Object saveDevice(@RequestBody QsgMeal entity) {
        try {
            if (null != entity.getPrice()) {
                entity.setIntegral(entity.getPrice().multiply(new BigDecimal(100)).intValue());
            }
            if (null == entity.getId()) {
                entity.setCreateDatetime(new Date());
                mealService.save(entity);
            }else {
                mealService.updateById(entity);
            }
            return new CommonResult().success(entity);
        } catch (Exception e) {
            e.printStackTrace();
            return new CommonResult().failed();
        }
    }

    @IgnoreAuth
    @ApiOperation("删除设备套餐表")
    @PostMapping(value = "/meal/delete")
    public Object deleteDevice(@RequestBody QsgMeal meal) {
        try {
            if (ValidatorUtils.empty(meal.getId())) {
                return new CommonResult().paramFailed("设备套餐表id");
            }
            if (mealService.removeById(meal.getId())) {
                return new CommonResult().success();
            }
        } catch (Exception e) {
            return new CommonResult().failed();
        }
        return new CommonResult().failed();
    }

    @IgnoreAuth
    @GetMapping(value = "/meal/getMealById")
    @ApiOperation(value = "根据id查询套餐")
    public Object getMealById(Long mealId) {
        try {
            return new CommonResult().success(mealService.getById(mealId));
        } catch (Exception e) {
            e.printStackTrace();
            return new CommonResult().failed();
        }
    }

    @IgnoreAuth
    @GetMapping(value = "/meal/saleMeal")
    @ApiOperation(value = "特价套餐")
    public Object saleMeal(Long mealId) {
        try {
            QsgMeal meal = mealService.getById(mealId);
            String endDate = meal.getEndTime();//12:00:00
            String[] times = StringUtils.split(endDate, ":");
            int duration = meal.getDuration();
            Date today = new Date();
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(today);
            calendar.set(Calendar.HOUR_OF_DAY, Integer.valueOf(times[0]));
            calendar.set(Calendar.MINUTE, Integer.valueOf(times[1]));
            calendar.set(Calendar.SECOND, Integer.valueOf(times[2]));
            Date oneEndTime = calendar.getTime();//Fri Nov 18 12:00:00 CST 2022
            calendar.set(Calendar.HOUR_OF_DAY, calendar.get(Calendar.HOUR_OF_DAY) - duration);
            Date oneStartTime = calendar.getTime();//Fri Nov 18 08:00:00 CST 2022
            calendar.add(Calendar.DATE, 1);
            Date twoStartTime = calendar.getTime();
            calendar.add(Calendar.HOUR_OF_DAY, duration);
            Date twoEndTime = calendar.getTime();
            calendar.add(Calendar.DATE, 1);
            Date threeEndTime = calendar.getTime();
            calendar.set(Calendar.HOUR_OF_DAY, calendar.get(Calendar.HOUR_OF_DAY) - duration);
            Date threeStartTime = calendar.getTime();
            List<String> result = new ArrayList<>();
            result.add(DateUtil.dateToString(oneStartTime, "yyyy/MM/dd HH:mm"));
            result.add(DateUtil.dateToString(oneEndTime, "yyyy/MM/dd HH:mm"));
//            result.add(DateUtil.dateToString(twoStartTime,"yyyy/MM/dd HH:mm:ss")+"-"+DateUtil.dateToString(twoEndTime,"yyyy/MM/dd HH:mm:ss"));
//            result.add(DateUtil.dateToString(threeStartTime,"yyyy/MM/dd HH:mm:ss")+"-"+DateUtil.dateToString(threeEndTime,"yyyy/MM/dd HH:mm:ss"));
            return new CommonResult().success(result);
        } catch (Exception e) {
            e.printStackTrace();
            return new CommonResult().failed();
        }
    }

    @GetMapping(value = "/mealdelete")
    public Object delete(@RequestParam Long id) {
        try {
            if (mealService.removeById(id)) {
                return new CommonResult().success();
            }
        } catch (Exception e) {
            return new CommonResult().failed();
        }
        return new CommonResult().failed();
    }

    @IgnoreAuth
    @GetMapping(value = "/meal/currentOrder")
    @ApiOperation(value = "正在进行的订单")
    public Object currentOrder(Long deviceId) {
        try {
            Date date = new Date();
            String now = DateUtil.dateToString(date,"yyyy/MM/dd HH:mm:ss");
            QueryWrapper qw = new QueryWrapper();
            qw.le("start_time",now);
            qw.ge("end_time",now);
            qw.eq("device_id",deviceId);
            qw.eq("order_status", OrderStatus.HAS_PAYMONEY.getValue());
            qw.orderByAsc("start_time");
            List<DmsOrder> orders = orderService.list(qw);
            return new CommonResult().success(orders);
        }catch (Exception e){
            e.printStackTrace();
            return new CommonResult().failed();
        }
    }

    @IgnoreAuth
    @GetMapping(value = "/meal/yuyueOrder")
    @ApiOperation(value = "已经被预约的订单")
    public Object yuyueOrder(Long deviceId, @RequestParam(required = false) String startTime, @RequestParam(required = false) String endTime) {
        try {
            QsgDevice device = deviceService.getById(deviceId);
            Date date = new Date();
            String now = DateUtil.dateToString(date, "yyyy/MM/dd HH:mm:ss");
            String[] nows = StringUtils.split(now, " ");
            String todayLast = nows[0] + " 23:59:59";
            QueryWrapper qw = new QueryWrapper();
            qw.ge("start_time", now);
            qw.ge("end_time", now);
            qw.eq("device_id", deviceId);
            List<Integer> statues = new ArrayList<>();
            statues.add(OrderStatus.HAS_PAYMONEY.getValue());
            statues.add(OrderStatus.WAIT_CANNEL.getValue());
            qw.in("order_status", statues);
            qw.orderByAsc("start_time");
            List<DmsOrder> todayYuyue = orderService.list(qw);
            //跨天和第二天的预约单
            QueryWrapper qw1 = new QueryWrapper();
            qw1.ge("start_time", todayLast);
            qw1.ge("end_time", todayLast);
            qw1.eq("device_id", deviceId);
            qw1.in("order_status", statues);
            qw1.orderByAsc("start_time");
            List<DmsOrder> secondDayYuyue = orderService.list(qw1);

            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.le("start_time", now);
            queryWrapper.ge("end_time", now);
            queryWrapper.eq("device_id", deviceId);
            queryWrapper.eq("order_status", OrderStatus.HAS_PAYMONEY.getValue());
            queryWrapper.orderByAsc("start_time");
            List<DmsOrder> current = orderService.list(queryWrapper);

            if (null != todayYuyue && todayYuyue.size() > 0) {
                List<Integer> currentYuyueArea = new ArrayList<>();
                for (DmsOrder order : todayYuyue) {
                    for (int i = new Date(order.getStartTime()).getHours(); i < new Date(order.getStartTime()).getHours() + order.getDuration(); i++) {
                        currentYuyueArea.add(i);
                    }
                }
                device.setTodayYuyue(currentYuyueArea);
            }

            if (null != secondDayYuyue && secondDayYuyue.size() > 0) {
                List<Integer> secondYuyueArea = new ArrayList<>();
                for (DmsOrder order : secondDayYuyue) {
                    for (int i = new Date(order.getStartTime()).getHours(); i < new Date(order.getStartTime()).getHours() + order.getDuration(); i++) {
                        secondYuyueArea.add(i);
                    }
                }
                device.setSecondYuyue(secondYuyueArea);
            }

            if (current.size() > 0) {
                List<Integer> currentOrderArea = new ArrayList<>();
                for (int i = new Date(current.get(0).getStartTime()).getHours(); i < new Date(current.get(0).getStartTime()).getHours() + current.get(0).getDuration(); i++) {
                    currentOrderArea.add(i);
                }
                device.setCurrentOrderArea(currentOrderArea);
            }
            setTimeAxis(device);
            setTimeAxisSecond(device);
            return new CommonResult().success(device);
        } catch (Exception e) {
            e.printStackTrace();
            return new CommonResult().failed();
        }
    }

    private static QsgDevice setTimeAxisSecond(QsgDevice device) {
        List<Integer> yuyueTimeArea = device.getTodayYuyue();
        List<TimeAxis> timeAxies = new ArrayList<>();
        //可选
        String yes = "background:#E8E8E8;height:36rpx;width: 17rpx;margin-right: 10rpx;height: 17rpx;padding-left: 5rpx;border-radius: 5rpx;";
        //不可选
        String not = "background:#F04747;height:36rpx;width: 17rpx;margin-right: 10rpx;height: 17rpx;padding-left: 5rpx;border-radius: 5rpx;";
        //已选
        String already = "background:#0DA944;height:36rpx;width: 17rpx;margin-right: 10rpx;height: 17rpx;padding-left: 5rpx;border-radius: 5rpx;";
        for (int i = 0; i <= 23; i++) {
            TimeAxis timeAxis = new TimeAxis();
            timeAxis.setHour(i);
            if (null != yuyueTimeArea && yuyueTimeArea.size() > 0) {
                if (yuyueTimeArea.contains(i)) {
                    timeAxis.setStyle(not);
                }
            }
            if (StringUtils.isBlank(timeAxis.getStyle())) {
                int now = new Date().getHours();
                if (now > i) {
                    timeAxis.setStyle(yes);
                } else {
                    timeAxis.setStyle(yes);
                }
            }
            timeAxies.add(timeAxis);
        }
        device.setTimeAxesSecond(timeAxies);
        return device;
    }

    private static QsgDevice setTimeAxis(QsgDevice device) {
        List<Integer> currentTimeArea = device.getCurrentOrderArea();
        List<Integer> yuyueTimeArea = device.getTodayYuyue();
        List<TimeAxis> timeAxies = new ArrayList<>();
        //可选
        String yes = "background:#E8E8E8;height:36rpx;width: 17rpx;margin-right: 10rpx;height: 17rpx;padding-left: 5rpx;border-radius: 5rpx;";
        //不可选
        String not = "background:#F04747;height:36rpx;width: 17rpx;margin-right: 10rpx;height: 17rpx;padding-left: 5rpx;border-radius: 5rpx;";
        //已选
        String already = "background:#0DA944;height:36rpx;width: 17rpx;margin-right: 10rpx;height: 17rpx;padding-left: 5rpx;border-radius: 5rpx;";
        for (int i = 0; i <= 23; i++) {
            TimeAxis timeAxis = new TimeAxis();
            timeAxis.setHour(i);
            if (null != currentTimeArea && currentTimeArea.size() > 0) {
                if (currentTimeArea.contains(i)) {
                    timeAxis.setStyle(not);
                }
            }
            if (null != yuyueTimeArea && yuyueTimeArea.size() > 0) {
                if (yuyueTimeArea.contains(i)) {
                    timeAxis.setStyle(not);
                }
            }
            if (StringUtils.isBlank(timeAxis.getStyle())) {
                int now = new Date().getHours();
                if (now > i) {
                    timeAxis.setStyle(not);
                } else {
                    timeAxis.setStyle(yes);
                }
            }
            timeAxies.add(timeAxis);
        }
        device.setTimeAxes(timeAxies);
        return device;
    }
}
